<template>
    <div class="login" :style="`background-image: url(${siteConfig.site_back_image || backgroundImage})`">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
            <h2 class="title">帆洲科技管理系统</h2>
            <el-tabs v-model="activeName">
                <el-tab-pane label="授权登录" name="authorize">
                    <el-form-item style="width: 100%; text-align: center; margin-top: 20px">
                        <div id="login_container" ></div>
                    </el-form-item>
                </el-tab-pane>
                <el-tab-pane label="手机号登录" name="phone" style="padding-top: 24px">
                    <el-form-item prop="tel">
                        <el-input v-model="loginForm.tel" type="text" auto-complete="off" placeholder="请输入手机号">
                            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
                        </el-input>
                    </el-form-item>
                    <!-- <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码" @keyup.enter.native="handleLogin">
                    <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
                </el-input>
            </el-form-item> -->
                    <el-form-item prop="checkCode" v-if="captchaOnOff">
                        <el-input v-model="loginForm.checkCode" auto-complete="off" placeholder="请输入验证码" style="width: 63%" @keyup.enter.native="handleLogin">
                            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
                        </el-input>
                        <div class="login-code">
                            <el-button :loading="isLoading" size="medium" type="primary" style="width: 100%" @click="handleSendVerificationCode">
                                <span v-if="!isLoading && !countdown">{{ buttonText }}</span>
                                <span v-else>{{ countdownText }}</span>
                            </el-button>
                        </div>
                    </el-form-item>
                    <el-checkbox v-model="loginForm.is_keeplogin" style="margin: 0px 0px 25px 0px">保持会话</el-checkbox>
                    <el-form-item style="width: 100%">
                        <el-button :loading="loading" size="medium" type="primary" style="width: 100%" @click.native.prevent="handleLogin">
                            <span v-if="!loading">登 录</span>
                            <span v-else>登 录 中...</span>
                        </el-button>
                    </el-form-item>
                </el-tab-pane>
            </el-tabs>
        </el-form>
        <!--  底部  -->
        <!-- <div class="el-login-footer">
            <span>{{ siteConfig.site_copyright || 'Copyright © 2018-2021 QuickAdmin.icu All Rights Reserved.' }}</span>
            <br />
            <span
                ><a href="https://beian.miit.gov.cn" target="_blank">{{ siteConfig.site_beian }}</a></span
            >
        </div> -->
        <!-- <div class="el-login-footer">
            <span>深圳帆洲科技有限公司  &nbsp;</span>
            <span>&nbsp;深圳市龙岗区龙城街道尚景社区龙城大道89号西门正中时代大厦A栋2602C-01, 518029 Shenzhen&nbsp;</span>
            <span>&nbsp;+8618802702771</span>
        </div> -->
    </div>
</template>

<script>
import { getCodeImg } from '@/api/login'
import { getConfig } from '@/api/system/config'
import Cookies from 'js-cookie'

export default {
    name: 'Login',
    data() {
        return {
            activeName: 'phone',
            codeUrl: '',
            cookiePassword: '',
            loginForm: {
                username: '',
                tel: '',
                password: '',
                is_keeplogin: true,
                checkCode: '',
                key: '',
            },
            loginRules: {
                tel: [{ required: true, trigger: 'blur', message: '请输入您的手机号' }],
            },
            loading: false,
            // 验证码开关
            captchaOnOff: true,
            redirect: undefined,
            logo: require('@/assets/logo/logo.png'),
            backgroundImage: process.env.VUE_APP_BASE_API + '/storage/system/login.jpg',
            siteConfig: {},

            //发短信倒计时
            isLoading: false,
            countdown: null, // 用于存储倒计时的间隔ID
            countdownTime: 60, // 倒计时秒数，例如60秒
            buttonText: '获取验证码',
            countdownText: '发送中...', // 初始倒计时文本，可以根据需要修改
            // 飞书登录相关
            goto: 'https://passport.feishu.cn/suite/passport/oauth/authorize?client_id=cli_a65d606753f9d00e&redirect_uri=https://fan-zhou.com/index&response_type=code&state=STATE'
        }
    },
    watch: {
        $route: {
            handler: function (route) {
                // this.redirect = route.query && route.query.redirect
                this.redirect = window.sessionStorage.getItem('login_redirect') ?? ''
            },
            immediate: true,
        },
    },
    created() {
        this.getCode()
        this.getCookie()
        this.config()
        this.initLarkLogin() // 初始化飞书登录
    },
    methods: {
        getCode() {
            getCodeImg().then(res => {
                this.captchaOnOff = res.captchaOnOff === undefined ? true : res.captchaOnOff
                if (this.captchaOnOff) {
                    this.loginForm.key = Cookies.get('key')
                    this.codeUrl = 'data:image/png;base64,' + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))
                }
            })
        },
        getCookie() {
            const tel = Cookies.get('tel')
            // const username = Cookies.get('username')
            // const password = Cookies.get('password')
            // const is_keeplogin = Cookies.get('is_keeplogin')
            this.loginForm = {
                tel: tel === undefined ? this.loginForm.tel : tel,
                username: this.loginForm.username,
                password: this.loginForm.password,
                is_keeplogin: false,
            }
        },
        handleLogin() {
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loading = true
                    if (this.loginForm.is_keeplogin) {
                        Cookies.set('tel', this.loginForm.tel, { expires: 30 })
                        // Cookies.set('username', this.loginForm.username, { expires: 30 })
                        // Cookies.set('password', encrypt(this.loginForm.password), {
                        //     expires: 30,
                        // })
                        // Cookies.set('is_keeplogin', this.loginForm.is_keeplogin, {
                        //     expires: 30,
                        // })
                    } else {
                        Cookies.remove('tel')
                        // Cookies.remove('username')
                        // Cookies.remove('password')
                        // Cookies.remove('is_keeplogin')
                    }
                    if (!/^\d+$/.test(this.loginForm.tel)) {
                        this.$message.error('电话号码必须为数字')
                        return
                    }
                    this.$store
                        .dispatch('Login', this.loginForm)
                        .then(() => {
                            this.$router.push({ path: this.redirect || '/' }).catch(() => {})
                        })
                        .catch(err => {
                            this.loading = false

                            if (this.captchaOnOff) {
                                this.getCode()
                            }
                        })
                }
            })
        },

        //获取系统配置
        config() {
            getConfig().then(response => {
                this.siteConfig = response.data
            })
        },

        //发短信倒计时
        handleSendVerificationCode() {
            if (this.isLoading || this.countdown) return // 如果已经在加载或倒计时中，则不执行
            this.isLoading = true
            this.buttonText = '' // 清空按钮文本

            this.sendsms()
            // 开始倒计时
            let countdownNumber = this.countdownTime
            this.countdown = setInterval(() => {
                countdownNumber--
                this.countdownText = `${countdownNumber} 秒`

                if (countdownNumber <= 0) {
                    clearInterval(this.countdown) // 清除倒计时
                    this.countdown = null
                    this.isLoading = false
                    this.buttonText = '发送验证码' // 重置按钮文本
                }
            }, 1000) // 每秒更新一次
        },
        sendsms() {
            this.loading = true
            this.request
                .post('/admin/admin/sendSms', { tel: this.loginForm.tel, smsType: 1 })
                .then(response => {
                    // this.$message.success('已发送');
                })
                .finally(() => {
                    this.loading = false
                    // this.$message.success('已发送');
                    // this.initIndex();
                })
        },
        // 飞书授权登录
        initLarkLogin() {
            const script = document.createElement('script');
            script.src = 'https://lf-package-cn.feishucdn.com/obj/feishu-static/lark/passport/qrcode/LarkSSOSDKWebQRCode-1.0.3.js';
            script.onload = () => {
                const QRLoginObj = QRLogin({
                    id: 'login_container',
                    goto: this.goto, // 替换为你的实际参数
                    width: '240',
                    height: '250',
                    style: 'width:300px; height:300px; border: none', // 可选，二维码 HTML 标签的样式
                });

            // 添加授权回调监听
            const handleMessage = (event) => {
                if (QRLoginObj.matchOrigin(event.origin) && QRLoginObj.matchData(event.data)) {
                    const loginTmpCode = event.data.tmp_code;
                    // 在授权页面地址上拼接上参数 tmp_code，并跳转
                    const gotoUrl = `${this.goto}&tmp_code=${loginTmpCode}`;
                    window.location.href = gotoUrl;
                }
            };

            if (typeof window.addEventListener !== 'undefined') {
                window.addEventListener('message', handleMessage, false);
            } else if (typeof window.attachEvent !== 'undefined') {
                window.attachEvent('onmessage', handleMessage);
            }
            };
            document.body.appendChild(script);
        },
    },

    //发短信倒计时
    beforeDestroy() {
        // 在组件销毁前清除倒计时，避免内存泄漏
        if (this.countdown) {
            clearInterval(this.countdown)
            this.countdown = null
        }
    },
}
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    background-image: url('../assets/images/quick_admin_login_bg.jpg');
    background-size: cover;
}
.title {
    margin: 10px auto 30px auto;
    text-align: center;
}
.description {
    margin: 10px auto;
    text-align: center;
    color: #ffffff;
}
.login-form {
    border-radius: 6px;
    // background: rgba(0, 0, 0, 0.5);
    background: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    width: 400px;
    min-height: 520px;
    padding: 25px 25px 5px 25px;
    // margin-right: 15%;
    .el-input {
        height: 38px;
        input {
            height: 38px;
        }
    }
    .input-icon {
        height: 39px;
        width: 14px;
        margin-left: 2px;
    }
}
.login-tip {
    font-size: 13px;
    text-align: center;
    color: #bfbfbf;
}
.login-code {
    width: 33%;
    height: 38px;
    float: right;
    img {
        cursor: pointer;
        vertical-align: middle;
    }
}
.el-login-footer {
    background-color: #000;
    font-size: 10px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #d4d4d4;
    font-family: Arial;
    letter-spacing: 1px;
}
.login-code-img {
    height: 38px;
}
</style>
